package com.cas.jms;

import com.cas.annotation.Mq;
import com.cas.jms.parser.Parser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class ParserFactory {
    private final ApplicationContext applicationContext;

    @Autowired
    public ParserFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public Parser getParser(String name) {
        String[] parserNames = applicationContext.getBeanNamesForAnnotation(Mq.class);

        for (String parserName : parserNames) {
            Parser parser = applicationContext.getBean(parserName, Parser.class);
            Mq mqAnnotation = parser.getClass().getAnnotation(Mq.class);
            if (mqAnnotation != null && mqAnnotation.name().equals(name)) {
                return parser;
            }
        }

        return null; // 找不到匹配的Parser
    }

    public List<String> getAllParserNames() {
        Map<String, Parser> parserBeans = applicationContext.getBeansOfType(Parser.class);
        List<String> parserNames = new ArrayList<>();

        for (Parser parser : parserBeans.values()) {
            Mq mqAnnotation = parser.getClass().getAnnotation(Mq.class);
            if (mqAnnotation != null) {
                parserNames.add(mqAnnotation.name());
            }
        }

        return parserNames;
    }
}
